package cvm

import (
	"context"
	"time"

	"gitee.com/go-course/go11/devcloud-mini/cmdb/apps/resource"
	"gitee.com/go-course/go11/devcloud-mini/cmdb/provider"
	"github.com/alibabacloud-go/tea/tea"
	cvm "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm/v20170312"
)

func (c *CVMClient) QueryHost(
	ctx context.Context,
	in *provider.QueryHostRequest,
	fn provider.HostHandler) error {
	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := cvm.NewDescribeInstancesRequest()

	// 返回的resp是一个DescribeInstancesResponse的实例，与请求对象对应
	response, err := c.c.DescribeInstances(request)
	if err != nil {
		return err
	}

	for i := range response.Response.InstanceSet {
		item := response.Response.InstanceSet[i]
		// 腾讯云CVM Object ---> Resource
		// 转换完成后 通过回调函数交给外部处理
		fn(c.Transfer(item))
	}

	return nil
}

// a<InstanceId> <--> c
// a<instance_id>
// a<id>
func (c *CVMClient) Transfer(ins *cvm.Instance) *resource.Resource {
	r := resource.NewResource()
	r.Spec.Type = resource.TYPE_HOST
	r.Meta.Id = tea.StringValue(ins.InstanceId)

	// 2023-08-12T08:01:21Z
	t, err := time.Parse("2006-01-02T03:04:05Z", tea.StringValue(ins.CreatedTime))
	if err != nil {
		panic(err)
	}
	r.Meta.CreateAt = t.Unix()
	r.Spec.Name = tea.StringValue(ins.InstanceName)
	r.Spec.Class = tea.StringValue(ins.InstanceType)
	r.Spec.Provider = resource.PROVIDER_TENCENT
	r.Spec.Region = c.region
	r.Spec.Zone = tea.StringValue(ins.Placement.Zone)
	// 如果你做多云的实例统一, 一定要统一多用的状态
	r.Spec.Status = tea.StringValue(ins.InstanceState)
	r.Spec.PrivateAddress = tea.StringSliceValue(ins.PrivateIpAddresses)
	r.Spec.Cpu = int32(tea.Int64Value(ins.CPU))
	// 我们的单位是M
	r.Spec.Memory = tea.Int64Value(ins.Memory) * 1024

	r.Spec.Storage = tea.Int64Value(ins.SystemDisk.DiskSize)
	if len(ins.DataDisks) > 0 {
		for i := range ins.DataDisks {
			dd := ins.DataDisks[i]
			r.Spec.Storage += tea.Int64Value(dd.DiskSize)
		}
	}

	//
	r.Spec.Extra["os_name"] = tea.StringValue(ins.OsName)
	return r
}
